<?php
namespace App\Models;

use App\Config\Database;
use PDO;
use PDOException;

/**
 * 媒体文件模型
 * @package App\Models
 * @description:
 * 1. 保存媒体文件信息
 * 2. 获取媒体文件信息
 * 3. 清理过期文件
 */
class MediaFile {
    private $conn;
    private $table = 'media_files';

    public $id;
    public $file_key;
    public $file_name;
    public $file_type;
    public $file_size;
    public $url;
    public $uploader_id;
    public $expires_at;
    public $created_at;

    public function __construct() {
        $database = new Database();
        $this->conn = $database->getConnection();
    }

    /**
     * 保存媒体文件信息
     * @return bool
     */
    public function save() {
        try {
            $query = "INSERT INTO " . $this->table . " 
                (file_key, file_name, file_type, file_size, url, uploader_id, expires_at) 
                VALUES 
                (:file_key, :file_name, :file_type, :file_size, :url, :uploader_id, :expires_at)";
            
            $stmt = $this->conn->prepare($query);
            
            // 绑定参数
            $stmt->bindParam(':file_key', $this->file_key);
            $stmt->bindParam(':file_name', $this->file_name);
            $stmt->bindParam(':file_type', $this->file_type);
            $stmt->bindParam(':file_size', $this->file_size);
            $stmt->bindParam(':url', $this->url);
            $stmt->bindParam(':uploader_id', $this->uploader_id);
            $stmt->bindParam(':expires_at', $this->expires_at);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            // 唯一键冲突表示已存在
            if ($e->getCode() == 23000) {
                return true; // 已存在，视为成功
            }
            error_log("Save media file error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 通过文件Key获取文件信息
     * @param string $fileKey 文件Key
     * @return array|null
     */
    public function getByFileKey($fileKey) {
        try {
            $query = "SELECT * FROM " . $this->table . " WHERE file_key = :file_key LIMIT 1";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':file_key', $fileKey);
            $stmt->execute();
            
            return $stmt->fetch(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Get media file by key error: " . $e->getMessage());
            return null;
        }
    }

    /**
     * 通过上传者ID获取文件列表
     * @param int $uploaderId 上传者ID
     * @param int $page 页码
     * @param int $pageSize 每页数量
     * @return array
     */
    public function getByUploader($uploaderId, $page = 1, $pageSize = 20) {
        try {
            $offset = ($page - 1) * $pageSize;
            
            $query = "SELECT * FROM " . $this->table . " 
                      WHERE uploader_id = :uploader_id
                      ORDER BY created_at DESC
                      LIMIT :offset, :limit";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':uploader_id', $uploaderId);
            $stmt->bindParam(':offset', $offset, PDO::PARAM_INT);
            $stmt->bindParam(':limit', $pageSize, PDO::PARAM_INT);
            
            $stmt->execute();
            return $stmt->fetchAll(PDO::FETCH_ASSOC);
        } catch (PDOException $e) {
            error_log("Get media files by uploader error: " . $e->getMessage());
            return [];
        }
    }

    /**
     * 清理过期文件
     * @return bool
     */
    public function cleanExpiredFiles() {
        try {
            $currentTime = date('Y-m-d H:i:s');
            $query = "DELETE FROM " . $this->table . " WHERE expires_at < :current_time";
            
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':current_time', $currentTime);
            
            return $stmt->execute();
        } catch (PDOException $e) {
            error_log("Clean expired files error: " . $e->getMessage());
            return false;
        }
    }

    /**
     * 检查文件是否存在
     * @param string $fileKey 文件Key
     * @return bool
     */
    public function exists($fileKey) {
        try {
            $query = "SELECT COUNT(*) as count FROM " . $this->table . " WHERE file_key = :file_key";
            $stmt = $this->conn->prepare($query);
            $stmt->bindParam(':file_key', $fileKey);
            $stmt->execute();
            
            $result = $stmt->fetch(PDO::FETCH_ASSOC);
            return $result['count'] > 0;
        } catch (PDOException $e) {
            error_log("Check file exists error: " . $e->getMessage());
            return false;
        }
    }
}